package com.netrust.cmsx.core.page.jq.convert;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.Page;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.netrust.cmsx.core.page.jq.JqGrid;
import com.netrust.cmsx.core.page.jq.JqRow;
import com.netrust.cmsx.utils.relfect.Reflections;

public class Page2JQ<T> {
	
	public Page2JQ() {
		super();
	}
	
	public JqGrid run(Page<T> page,String[] properties){
		JqGrid jg=new JqGrid();
		jg.setPage(String.valueOf(page.getNumber()+1));
		jg.setTotal(page.getTotalPages());
		jg.setRecords(String.valueOf(page.getTotalElements()));
		
		jg.setRows(this.p2jr(page.getContent(),properties));
		
		return jg;
	}
	
	
	private List<JqRow> p2jr(List<T> list,String[] properties) {
		List<JqRow> jqs =new ArrayList<JqRow>();
		
		for (int i = 0; i < list.size(); i++) {
			JqRow jq=new JqRow();
			
			jq.setId(Reflections.getFieldValue(list.get(i),"id").toString());
			
			String [] pv=new String[properties.length];
			for (int j = 0; j < properties.length; j++) {
				Object obj=Reflections.getFieldValue(list.get(i),properties[j]);
				if(obj!=null){
					pv[j]=Reflections.getFieldValue(list.get(i),properties[j]).toString();					
				}else{
					pv[j]=null;
				}
			}
			
			jq.setCell(pv);
			
			jqs.add(jq);
		}
		
		return jqs;
	}
	
}
